package com.example.demo.commons.result.common.exception;


import com.example.demo.commons.result.able.ErrorCodeInterface;
import com.example.demo.commons.result.able.ExceptionInterface;
import com.example.demo.commons.result.common.entity.BizResult;
import lombok.*;


/**
 * <p> 业务异常 </p>
 *
 * @author tanyunpeng
 * @date 2021/11/18
 */
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
@Getter
@Setter(AccessLevel.PRIVATE)
public class BizException extends RuntimeException implements ExceptionInterface {

    @NonNull
    private String code;

    @NonNull
    private String msg;

    private BizException(String code, String msg) {
        super(msg);
        this.code = code;
        this.msg = msg;
    }

    private static BizException of(String code, String msg) {
        return new BizException(code, msg);
    }

    /**
     * @param error 错误码枚举
     */
    public static BizException create(@NonNull ErrorCodeInterface error) {
        return BizException.of(error.getCode(), error.getDesc());
    }

    /**
     * @param error        错误码
     * @param errorMessage 自定义错误信息
     */
    public static BizException create(@NonNull ErrorCodeInterface error, @NonNull String errorMessage) {
        if (errorMessage.isEmpty() || errorMessage.trim().isEmpty()) {
            return BizException.of(error.getCode(), error.getDesc());
        }
        return BizException.of(error.getCode(), errorMessage);
    }

    /**
     * @param bizResult 错误结果集
     */
    public static BizException create(@NonNull BizResult bizResult) {
        return BizException.of(bizResult.getCode(), bizResult.getMsg());
    }
}